// 主JavaScript文件

// DOM加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
    // 初始化侧边栏
    initSidebar();
    
    // 初始化顶部导航栏
    initTopNavbar();
    
    // 初始化响应式布局
    initResponsiveLayout();
    
    // 初始化导航高亮
    initNavHighlight();
    
    // 添加全局事件监听
    addGlobalEventListeners();
    
    // 模拟数据加载完成后隐藏加载状态
    simulateDataLoading();
});

// 初始化侧边栏
function initSidebar() {
    const sidebar = document.querySelector('.sidebar');
    const menuToggle = document.getElementById('menuToggle');
    const mainContent = document.querySelector('.main-content');
    
    if (menuToggle) {
        menuToggle.addEventListener('click', function() {
            sidebar.classList.toggle('active');
            
            // 在移动设备上，点击菜单按钮后自动关闭
            if (window.innerWidth <= 992) {
                // 点击其他区域关闭侧边栏
                document.addEventListener('click', closeSidebarOnOutsideClick);
            }
        });
    }
    
    // 阻止侧边栏内的点击事件冒泡
    if (sidebar) {
        sidebar.addEventListener('click', function(e) {
            e.stopPropagation();
        });
    }
    
    function closeSidebarOnOutsideClick(e) {
        if (!sidebar.contains(e.target) && e.target !== menuToggle) {
            sidebar.classList.remove('active');
            document.removeEventListener('click', closeSidebarOnOutsideClick);
        }
    }
}

// 初始化顶部导航栏
function initTopNavbar() {
    // 初始化用户头像下拉菜单
    const userProfile = document.querySelector('.user-profile');
    if (userProfile) {
        userProfile.addEventListener('click', function() {
            // 这里可以实现用户下拉菜单
            console.log('用户菜单点击');
        });
    }
    
    // 初始化通知图标点击事件
    const notification = document.querySelector('.notification');
    if (notification) {
        notification.addEventListener('click', function() {
            // 这里可以实现通知面板
            console.log('通知点击');
        });
    }
    
    // 初始化搜索框
    const searchBox = document.querySelector('.search-box input');
    if (searchBox) {
        searchBox.addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                e.preventDefault();
                performSearch(searchBox.value);
            }
        });
    }
}

// 执行搜索
function performSearch(keyword) {
    if (keyword.trim()) {
        console.log('搜索关键词:', keyword);
        // 这里可以实现实际的搜索逻辑
    }
}

// 初始化响应式布局
function initResponsiveLayout() {
    function adjustLayout() {
        const sidebar = document.querySelector('.sidebar');
        const mainContent = document.querySelector('.main-content');
        
        if (window.innerWidth <= 992) {
            sidebar.classList.remove('active');
        } else {
            sidebar.classList.add('active');
        }
    }
    
    // 初始调整
    adjustLayout();
    
    // 监听窗口大小变化
    window.addEventListener('resize', debounce(adjustLayout, 300));
}

// 初始化导航高亮
function initNavHighlight() {
    const navItems = document.querySelectorAll('.nav-item');
    const currentPath = window.location.pathname;
    
    navItems.forEach(item => {
        const link = item.querySelector('.nav-link');
        const href = link.getAttribute('href');
        
        // 比较当前路径和导航链接
        if (currentPath.includes(href)) {
            item.classList.add('active');
        } else {
            item.classList.remove('active');
        }
    });
}

// 添加全局事件监听
function addGlobalEventListeners() {
    // 为所有按钮添加波纹效果
    document.querySelectorAll('button, .btn').forEach(button => {
        button.addEventListener('click', createRippleEffect);
    });
    
    // 为所有链接添加导航效果
    document.querySelectorAll('a').forEach(link => {
        link.addEventListener('click', function(e) {
            // 阻止默认行为，添加导航动画
            const href = this.getAttribute('href');
            if (href && !href.startsWith('#') && !href.startsWith('javascript:')) {
                // 这里可以添加页面切换动画
                console.log('导航到:', href);
            }
        });
    });
}

// 创建波纹效果
function createRippleEffect(e) {
    const button = e.currentTarget;
    const circle = document.createElement('span');
    const diameter = Math.max(button.clientWidth, button.clientHeight);
    const radius = diameter / 2;
    
    circle.style.width = circle.style.height = `${diameter}px`;
    circle.style.left = `${e.clientX - button.getBoundingClientRect().left - radius}px`;
    circle.style.top = `${e.clientY - button.getBoundingClientRect().top - radius}px`;
    circle.classList.add('ripple');
    
    const ripple = button.getElementsByClassName('ripple')[0];
    if (ripple) {
        ripple.remove();
    }
    
    button.appendChild(circle);
}

// 模拟数据加载
function simulateDataLoading() {
    // 模拟页面加载完成后的动画
    document.body.classList.add('loaded');
    
    // 可以在这里添加数据加载的模拟逻辑
}

// 防抖函数
function debounce(func, wait) {
    let timeout;
    return function() {
        const context = this;
        const args = arguments;
        clearTimeout(timeout);
        timeout = setTimeout(() => func.apply(context, args), wait);
    };
}

// 节流函数
function throttle(func, limit) {
    let inThrottle;
    return function() {
        const context = this;
        const args = arguments;
        if (!inThrottle) {
            func.apply(context, args);
            inThrottle = true;
            setTimeout(() => inThrottle = false, limit);
        }
    };
}

// 显示提示信息
function showToast(message, type = 'info', duration = 3000) {
    // 创建提示框元素
    const toast = document.createElement('div');
    toast.className = `toast toast-${type}`;
    toast.textContent = message;
    
    // 添加到页面
    document.body.appendChild(toast);
    
    // 设置动画
    setTimeout(() => {
        toast.classList.add('show');
    }, 10);
    
    // 设置自动关闭
    setTimeout(() => {
        toast.classList.remove('show');
        setTimeout(() => {
            document.body.removeChild(toast);
        }, 300);
    }, duration);
    
    // 添加关闭按钮样式和事件
    const style = document.createElement('style');
    style.textContent = `
        .toast {
            position: fixed;
            top: 20px;
            right: 20px;
            padding: 12px 20px;
            border-radius: 4px;
            color: white;
            font-size: 14px;
            z-index: 9999;
            transform: translateX(100%);
            transition: transform 0.3s ease;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
        }
        .toast.show {
            transform: translateX(0);
        }
        .toast-info {
            background-color: #3498db;
        }
        .toast-success {
            background-color: #27ae60;
        }
        .toast-error {
            background-color: #e74c3c;
        }
        .toast-warning {
            background-color: #f39c12;
        }
    `;
    document.head.appendChild(style);
}

// 格式化日期时间
function formatDateTime(date) {
    const d = new Date(date);
    const year = d.getFullYear();
    const month = String(d.getMonth() + 1).padStart(2, '0');
    const day = String(d.getDate()).padStart(2, '0');
    const hours = String(d.getHours()).padStart(2, '0');
    const minutes = String(d.getMinutes()).padStart(2, '0');
    const seconds = String(d.getSeconds()).padStart(2, '0');
    
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

// 格式化数字（添加千分位）
function formatNumber(num) {
    return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
}

// 获取URL参数
function getUrlParam(name) {
    const urlParams = new URLSearchParams(window.location.search);
    return urlParams.get(name);
}

// 复制到剪贴板
function copyToClipboard(text) {
    navigator.clipboard.writeText(text)
        .then(() => {
            showToast('复制成功', 'success');
        })
        .catch(err => {
            showToast('复制失败', 'error');
            console.error('复制失败:', err);
        });
}

// 检查元素是否在视口中
function isElementInViewport(el) {
    const rect = el.getBoundingClientRect();
    return (
        rect.top >= 0 &&
        rect.left >= 0 &&
        rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
        rect.right <= (window.innerWidth || document.documentElement.clientWidth)
    );
}

// 滚动到元素
function scrollToElement(element, offset = 0) {
    const elementPosition = element.getBoundingClientRect().top;
    const offsetPosition = elementPosition + window.pageYOffset + offset;
    
    window.scrollTo({
        top: offsetPosition,
        behavior: 'smooth'
    });
}

// 导出表格数据为CSV
function exportTableToCSV(tableId, filename = 'data.csv') {
    const table = document.getElementById(tableId);
    if (!table) {
        showToast('未找到表格元素', 'error');
        return;
    }
    
    let csv = [];
    
    // 获取表头
    const headers = table.querySelectorAll('thead th');
    const headerRow = Array.from(headers).map(header => header.textContent.trim());
    csv.push(headerRow.join(','));
    
    // 获取表格数据
    const rows = table.querySelectorAll('tbody tr');
    rows.forEach(row => {
        const cells = row.querySelectorAll('td');
        const rowData = Array.from(cells).map(cell => {
            // 处理包含逗号的内容
            const text = cell.textContent.trim();
            return text.includes(',') ? `"${text}"` : text;
        });
        csv.push(rowData.join(','));
    });
    
    // 创建下载链接
    const csvContent = csv.join('\n');
    const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
    const link = document.createElement('a');
    
    if (link.download !== undefined) {
        const url = URL.createObjectURL(blob);
        link.setAttribute('href', url);
        link.setAttribute('download', filename);
        link.style.visibility = 'hidden';
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        URL.revokeObjectURL(url);
    }
    
    showToast('导出成功', 'success');
}

// 打印页面
function printPage() {
    window.print();
}

// 检测设备类型
function detectDevice() {
    const isMobile = window.innerWidth <= 768;
    const isTablet = window.innerWidth > 768 && window.innerWidth <= 1024;
    const isDesktop = window.innerWidth > 1024;
    
    return {
        isMobile,
        isTablet,
        isDesktop
    };
}

// 添加CSS类到元素
function addClass(element, className) {
    if (element && !element.classList.contains(className)) {
        element.classList.add(className);
    }
}

// 移除CSS类从元素
function removeClass(element, className) {
    if (element && element.classList.contains(className)) {
        element.classList.remove(className);
    }
}

// 切换CSS类
function toggleClass(element, className) {
    if (element) {
        element.classList.toggle(className);
    }
}

// 获取元素的样式
function getStyle(element, property) {
    return window.getComputedStyle(element).getPropertyValue(property);
}

// 设置元素的样式
function setStyle(element, property, value) {
    if (element) {
        element.style[property] = value;
    }
}

// 淡入效果
function fadeIn(element, duration = 300) {
    element.style.opacity = '0';
    element.style.display = 'block';
    
    let start = null;
    function animation(currentTime) {
        if (!start) start = currentTime;
        const progress = currentTime - start;
        element.style.opacity = progress / duration;
        
        if (progress < duration) {
            requestAnimationFrame(animation);
        } else {
            element.style.opacity = '1';
        }
    }
    
    requestAnimationFrame(animation);
}

// 淡出效果
function fadeOut(element, duration = 300) {
    element.style.opacity = '1';
    
    let start = null;
    function animation(currentTime) {
        if (!start) start = currentTime;
        const progress = currentTime - start;
        element.style.opacity = 1 - (progress / duration);
        
        if (progress < duration) {
            requestAnimationFrame(animation);
        } else {
            element.style.opacity = '0';
            element.style.display = 'none';
        }
    }
    
    requestAnimationFrame(animation);
}

// 添加全局样式
const globalStyles = document.createElement('style');
globalStyles.textContent = `
    /* 波纹效果样式 */
    .ripple {
        position: absolute;
        border-radius: 50%;
        background-color: rgba(255, 255, 255, 0.5);
        transform: scale(0);
        animation: ripple-animation 0.6s linear;
        pointer-events: none;
    }
    
    @keyframes ripple-animation {
        to {
            transform: scale(4);
            opacity: 0;
        }
    }
    
    /* 页面加载动画 */
    .loaded {
        transition: opacity 0.3s ease;
    }
    
    /* 滚动动画 */
    .scroll-animate {
        opacity: 0;
        transform: translateY(20px);
        transition: opacity 0.6s ease, transform 0.6s ease;
    }
    
    .scroll-animate.visible {
        opacity: 1;
        transform: translateY(0);
    }
`;
document.head.appendChild(globalStyles);

// 暴露全局方法
window.utils = {
    showToast,
    formatDateTime,
    formatNumber,
    getUrlParam,
    copyToClipboard,
    isElementInViewport,
    scrollToElement,
    exportTableToCSV,
    printPage,
    detectDevice,
    addClass,
    removeClass,
    toggleClass,
    getStyle,
    setStyle,
    fadeIn,
    fadeOut,
    debounce,
    throttle
};